import { Controller, Get, Header, HttpException, Req } from '@nestjs/common';
import config from 'config';
import { AppService } from './app.service';

type Route = { gitRepo: string; cdnRoot: string; url: string[] };
const routes = config.get<Route[]>('ROUTES');

const routeMap: { [key: string]: Route } = {};
routes.forEach(route => {
  for (const url of route.url) {
    routeMap[url] = route;
  }
});

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) { }
  // 健康检查
  @Get('/health')
  async getHello() {
    // 可以在这里实现各种健康检查逻辑
    return 'hello node-web-router-server'
  }

  @Get(Object.keys(routeMap))
  @Header('X-UA-Compatible', 'IE=edge,chrome=1')
  route(@Req() req) {
    // const logger = getLogger();
    const path = req.path.replace(/\/$/g, '');
    const route = routeMap[path];
    // console.log('.path',path)
    // if (!route) {
    //   logger.error('routeMap 中没有找到 %s 对应的路由', path);
    //   throw new HttpException('没有找到当前url对应的路由', 404);
    // }
    const cdnRoot = route.cdnRoot;
    return this.appService.fetchIndexHtml(cdnRoot);
  }
}